package game.classes;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Chris
 */
public class NetworkChannel implements Runnable {

    private static final int PORT = 6886;
    private ServerSocket server = null;
    private Socket client = null;
    private PrintWriter out;
    private BufferedReader in;
    private GameMode mode;

    public NetworkChannel(GameMode mode) {
        this.mode = mode;

    }

    public void close() {
        try {
            out.close();
            in.close();
            client.close();
            server.close();
        } catch (IOException e) {
        }
    }

    public void setupServer() {
        try {
            server = new ServerSocket(PORT);
        } catch (IOException e) {
            System.err.println("Problemas en el puerto: " + e.getMessage());
            System.exit(1);
        }

        try {
            client = server.accept();
        } catch (IOException e) {
            System.err.println("Intento de conexion fallido: " + e.getMessage());
            System.exit(1);
        }
        setBuffers();
    }

    public void setupClient(String ip) {
        try {
            client = new Socket(ip, PORT);
        } catch (UnknownHostException e) {
            System.err.println("No puedo encontrar el host: " + e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error al abrir socket: " + e.getMessage());
            System.exit(1);
        }
        setBuffers();
    }

    public void sendMessage(NetworkMessage m) {
        out.println(m.getPlainMessage());
    }

    private void setBuffers() {
        try {
            out = new PrintWriter(client.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        } catch (IOException e) {
            System.err.println("Fallo en los buffers: " + e.getMessage());
            System.exit(1);
        }
    }

    public void run() {
        String input;
        try {
            while ((input = in.readLine()) != null) {
                mode.notifyNetworkMessage(new NetworkMessage(input));
            }
        } catch (IOException e) {
            System.err.println("Se jodio el mensaje: " + e.getMessage());
            System.exit(1);
        }
    }
}
